package com.dqhl.community.activity;

import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.PixelFormat;
import android.graphics.drawable.Drawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.arrownock.exception.ArrownockException;
import com.arrownock.im.callback.AnIMGetClientsStatusCallbackData;
import com.arrownock.im.callback.IAnIMCallback;
import com.arrownock.im.callback.IAnIMGetClientIdCallback;
import com.arrownock.im.callback.IAnIMGetClientsStatusCallback;
import com.dqhl.community.R;
import com.dqhl.community.adapter.ChatAdapter;
import com.dqhl.community.base.BaseActivity;
import com.dqhl.community.model.ChatBean;
import com.dqhl.community.util.Constant;
import com.dqhl.community.util.Dlog;
import com.dqhl.community.util.ScreenUtils;
import com.dqhl.community.view.PictureSelectPopupWindow;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;

/**
 * Created by LIENLIN on 2016/9/6.
 * 创建anIM实例，并做初始化配置
 */
public class ChatActivity extends BaseActivity implements View.OnClickListener, AdapterView.OnItemClickListener, ChatAdapter.OnPictureClickListener {

    private IAnIMCallback callback = new MessageCallback(this);
//    private AnIM anIM;
//    private AnDesk anDesk;
    private String mClientId="123";
    private EditText mEtMessage;
    private TextView mBtnSend;//发送文本
    private ImageView mBtnSendImg;//发送图片
    private ImageView ivTopBack;
    private TextView tvTopTitle;
    private String clientId;//箭扣clientId
    private String username;
    private ListView mLvChar;
    private List<ChatBean> list=new ArrayList<>();
    private static int REQUESTCODE_PICTURE = 100;
    private static int REQUESTCODE_CAMERA = 101;
    Boolean status=false;//在线状态
    private PictureSelectPopupWindow pictureSelectPopupWindow; // 照片选择popupwindow
//    private final String TARGETCLIENTID = "AIMNLKLNNE576VN5VRKEDXA";//用户aaaa
//    private final String SERVER_KEY = "lubBdCWJoYeHWG0TPJUyWcc332XfvzDj";//appkey
    //private final String targetClientId = "AIM6NHUBJBT5K7Q1JHM2FJV";//用户testuser
    private ChatAdapter adapter;
    private String nikename;//昵称
    private String headImg;//头像路径

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_chat);

//        sp = getSharedPreferences(Constant.USER_INFO, MODE_PRIVATE);

//        userid=getIntent().getStringExtra("userid");
//        username=getIntent().getStringExtra("username");
        clientId=spUserInfo.getString(Constant.IM_CLIENTID,"");
        username=spUserInfo.getString(Constant.IM_USERNAME,"");//手机号
        nikename = spUserInfo.getString(Constant.NICKNAME, username);
        headImg = spUserInfo.getString(Constant.PHOTO_PATH, "");
        Log.d("ChatActivity",clientId+":"+ nikename+":"+headImg);
        initView();

    }
    @Override
    protected void onResume() {
        super.onResume();
        InitAnIm();

        //显示对方是否在线
        Boolean imStatus = getIMStatus();
        if (imStatus!=true){
           Log.d("ChatActivity", "对方已下线");
        }

        boolean connected = isConnected();
        //没有网络连接时
        if (connected==false){
            toast(R.string.error_net_connection);
        }
        adapter = new ChatAdapter(this,list,headImg);
        mLvChar.setAdapter(adapter);
        adapter.setOnPictureClickListener(this);
        mLvChar.setOnItemClickListener(this);
    }

    /**
     * 实例化AnIm
     */
    private void InitAnIm() {
        //实例化anIM
        anIM.setCallback(callback);
        //获取anIM为每一个的唯一客户端分配标识clientId
//        String userId =userid;//登录用户的userid
//        Log.d("ChatAdapter","userId="+userId);
//        anIM.getClientId(userId, new IAnIMGetClientIdCallback() {
//            @Override
//            public void onSuccess(String clientId) {
//
//                mClientId=clientId;
//                Log.d("ChatAdapter","mClientId="+mClientId);
//                //连接anIM服务器
        if (!TextUtils.isEmpty(clientId)){
            try {
                anIM.connect(clientId);
            } catch (ArrownockException e) {
                e.printStackTrace();
            }
        }else {
            Log.d("ChatActivity","clientId为空");
        }

//            }
//            @Override
//            public void onError(ArrownockException exception) {
//                Log.d("ChatActivity","clientId="+exception.toString());
//            }
//        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (data != null) {
            if (requestCode == REQUESTCODE_PICTURE && resultCode == RESULT_OK) {
                Uri selectedImage = geturi(data);
                String[] filePathColumns = {MediaStore.Images.Media.DATA};
                Cursor c = this.getContentResolver().query(selectedImage, filePathColumns, null, null, null);
                if (c != null) {
                    c.moveToFirst();
                    int columnIndex = c.getColumnIndex(filePathColumns[0]);
                    String picturePath = c.getString(columnIndex);
                    Dlog.e("picturePath=========" + picturePath);
                    c.close();
                    sendForPath(picturePath);
                }
            }
            if (requestCode == REQUESTCODE_CAMERA && resultCode == RESULT_OK) {
                String sdState = Environment.getExternalStorageState();
                if (!sdState.equals(Environment.MEDIA_MOUNTED)) {
                    Dlog.e("sd card unmount");
                }
                String name = UUID.randomUUID().toString() + ".jpg";
                File file = new File("/sdcard/pintu");
                file.mkdirs();
                Bundle bundle = data.getExtras();
                //获取相机返回的数据，并转换为图片格式
                Bitmap bitmap = (Bitmap) bundle.get("data");
                FileOutputStream fout = null;
                String fileName = file.getPath() + name;
                try {
                    fout = new FileOutputStream(fileName);
                    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fout);
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } finally {
                    try {
                        fout.flush();
                        fout.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                sendForPath(fileName);
            }
        }
    }

    /**
     * 发送二进制内容
     * @param path
     */
    private void sendForPath(String path){
        Log.d("ChatActivity","path="+path);

        Drawable drawable =Drawable.createFromPath(path);
        byte[] bytes = drawableToBitmap(drawable);

        Log.d("ChatAdapter",bytes.toString());
        if (bytes!=null){
//            String targetClientId = "AIMHLKRD5V0H66PQ3R7LLAL";//用户aaaa
            Map<String, String> customData = new HashMap<String, String>();
            customData.put("name", nikename);
//            customData.put("age", "31");
            try {
                String jpeg = anIM.sendBinary(Constant.TARGET_CLIENTID,bytes, "jpg",customData);
                //封装发送内容
                ChatBean chat=new ChatBean(jpeg,null,bytes,"jpg",mClientId);
//                Log.d("mClientId","mClientId="+mClientId);
                adapter.addList(chat);
                mLvChar.setSelection(adapter.getCount()-1);
                Log.d("sendBinary","sendBinary="+jpeg);
            } catch (ArrownockException e) {
                e.printStackTrace();
                Log.d("sendBinary","sendBinary="+e.toString());
            }
        }
    }
    private void initView() {

        mEtMessage = (EditText) findViewById(R.id.et_message);
        mBtnSend = (TextView) findViewById(R.id.btn_send);
        mBtnSendImg = (ImageView) findViewById(R.id.btn_sendimg);
        mLvChar = (ListView) findViewById(R.id.lv_char);
        ivTopBack = (ImageView) findViewById(R.id.iv_top_back);
        tvTopTitle = (TextView) findViewById(R.id.tv_top_title);
        //TODO nikename动态回去对方昵称
//        tvTopTitle.setText(nikename);
        tvTopTitle.setText("王医生");
        //动态设置高度
        int height= ScreenUtils.getScreenHeight(this);
        int px=ScreenUtils.dp2px(this, 115);
        RelativeLayout.LayoutParams params= (RelativeLayout.LayoutParams) mLvChar.getLayoutParams();
        params.height=height-px;
        mLvChar.setLayoutParams(params);
        mLvChar.setDividerHeight(0);

        ivTopBack.setVisibility(View.VISIBLE);
        mBtnSend.setOnClickListener(this);
        mBtnSendImg.setOnClickListener(this);
        ivTopBack.setOnClickListener(this);
        //初始化PopupWindow弹窗
        pictureSelectPopupWindow = new PictureSelectPopupWindow(this, pictureSelectItemsOnClick);
        pictureSelectPopupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                pictureSelectPopupWindow.backgroundAlpha(1.0f);
            }
        });

     }
    View.OnClickListener pictureSelectItemsOnClick = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            switch (view.getId()) {
                case R.id.btn_take_photo:   // 调用系统相机
                    Intent camera = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    startActivityForResult(camera, REQUESTCODE_CAMERA);
                    pictureSelectPopupWindow.dismiss();
                    break;
                case R.id.btn_pick_photo:   // 调取手机相册
                    Intent picture = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                    startActivityForResult(picture, REQUESTCODE_PICTURE);
                    pictureSelectPopupWindow.dismiss();
                    break;
                case R.id.btn_cancel:// 取消
                    pictureSelectPopupWindow.dismiss();
                    break;
            }
        }
    };
    @Override
    public void onClick(View view) {
        //发送私聊文本到指定好友
        switch (view.getId()){
            case R.id.btn_send:
                sendText();
                break;
            case R.id.btn_sendimg:
                sendImg();
                break;
            case R.id.iv_top_back:
                try {
                    anIM.disconnect();
                } catch (ArrownockException e) {
                    e.printStackTrace();
                    Log.d("ChatActivity","ArrownockException="+e.toString());
                }
                finish();
                break;
        }
    }
    @Override
    public void onBackPressed() {
        super.onBackPressed();
        try {
            anIM.disconnect();
        } catch (ArrownockException e) {
            e.printStackTrace();
        }
    }

    /**
     * 发送文本
     */
    private void sendText(){
        try {
            String message = mEtMessage.getText().toString();
            Map<String, String> customData = new HashMap<String, String>();
            customData.put("name",nikename);
//            customData.put("age", "31");
            String msgId = anIM.sendMessage(Constant.TARGET_CLIENTID, message, customData, true);
            //封装发送内容
//            Log.d("isWifiConnected","isWifiConnected="+isNetworkAvailable(this));
//            Log.d("isWifiConnected","IsStartWifi="+IsStartWifi(this));
//            if (isNetworkAvailable(this)==false){
//                mClientId="123";
//            }else {
//                if (IsStartWifi(this)==false){
//                    mClientId="123";
//                }
//            }
            ChatBean chat=new ChatBean(msgId,message,null,null,mClientId);
            Log.d("mClientId","mClientId="+mClientId);
            adapter.addList(chat);
            mLvChar.setSelection(adapter.getCount()-1);
            mEtMessage.setText("");
            Log.d("ChatActivity","msgId="+msgId);
        } catch (ArrownockException e) {
            e.printStackTrace();
        }
    }
    /**
     * 显示弹窗
     */
    private void sendImg(){
            pictureSelectPopupWindow.showAtLocation(findViewById(R.id.relative_chat), Gravity.BOTTOM, 0, 0);
            pictureSelectPopupWindow.backgroundAlpha(0.5f);
    }
    /**
     * 获取在线状态
     * @return
     */
    private Boolean getIMStatus(){
        Set<String >set=new HashSet<>();
        set.add(Constant.TARGET_CLIENTID);
        anIM.getClientsStatus(set, new IAnIMGetClientsStatusCallback() {
            @Override
            public void onSuccess(AnIMGetClientsStatusCallbackData anIMGetClientsStatusCallbackData) {
                Map<String, Boolean> clientsStatus = anIMGetClientsStatusCallbackData.getClientsStatus();
                Log.d("ChatActivity","clientsStatus.size()="+clientsStatus.size());
                status = clientsStatus.get(Constant.TARGET_CLIENTID);
                Log.d("ChatActivity","clientsStatus="+status);
            }
            @Override
            public void onError(ArrownockException e) {
            }
        });
        return status;
    }
    /**
     * 资源转换为图片资源
     * @param drawable
     * @return
     */
    public static byte[] drawableToBitmap(Drawable drawable) {

        int width = drawable.getIntrinsicWidth();
        int height = drawable.getIntrinsicHeight();
        Bitmap bitmap = Bitmap.createBitmap(width, height,
                drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888
                        : Bitmap.Config.RGB_565);
        Canvas canvas = new Canvas(bitmap);
        drawable.setBounds(0, 0, width, height);
        drawable.draw(canvas);

        ByteArrayOutputStream out = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
        try {
            out.flush();
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return out.toByteArray();
    }

    /**
     * 文本消息回传
     * @param chat
     */
    public void getMsg(final ChatBean chat){
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                adapter.addList(chat);
                mLvChar.setSelection(adapter.getCount()-1);
                adapter.notifyDataSetChanged();
                Log.d("ChatActivity","list.size()a="+list.size());
            }
        });
    }

    /**
     * 二进制消息回传
     * @param chat
     */
    public void getImg(final ChatBean chat) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                adapter.addList(chat);
                mLvChar.setSelection(adapter.getCount()-1);
                adapter.notifyDataSetChanged();
                Log.d("ChatActivity","list.size()="+list.size());
            }
        });

    }
    /**
     * 解决小米部分手机调用系统相册失败
     * @param intent
     * @return
     */
    public Uri geturi(android.content.Intent intent) {
        Uri uri = intent.getData();
        String type = intent.getType();
        if (uri.getScheme().equals("file") && (type.contains("image/"))) {
            String path = uri.getEncodedPath();
            if (path != null) {
                path = Uri.decode(path);
                ContentResolver cr = this.getContentResolver();
                StringBuffer buff = new StringBuffer();
                buff.append("(").append(MediaStore.Images.ImageColumns.DATA).append("=")
                        .append("'" + path + "'").append(")");
                Cursor cur = cr.query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                        new String[]{MediaStore.Images.ImageColumns._ID},
                        buff.toString(), null, null);
                int index = 0;
                for (cur.moveToFirst(); !cur.isAfterLast(); cur.moveToNext()) {
                    index = cur.getColumnIndex(MediaStore.Images.ImageColumns._ID);
                    // set _id value
                    index = cur.getInt(index);
                }
                if (index == 0) {
                    // do nothing
                } else {
                    Uri uri_temp = Uri
                            .parse("content://media/external/images/media/"
                                    + index);
                    if (uri_temp != null) {
                        uri = uri_temp;
                    }
                }
            }
        }
        return uri;
    }

    /**
     * 判断网络是否连接（）
     * @return
     */
    public boolean isConnected() {
        ConnectivityManager connectivity = (ConnectivityManager) this.getSystemService(Context.CONNECTIVITY_SERVICE);
        if (null != connectivity) {
            NetworkInfo info = connectivity.getActiveNetworkInfo();
            if (null != info && info.isConnected()) {
                if (info.getState() == NetworkInfo.State.CONNECTED) {
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * 检查当前网络是否可用
     * @param activity
     * @return
     */
    public boolean isNetworkAvailable(Context activity)
    {
        Context context = activity.getApplicationContext();
        // 获取手机所有连接管理对象（包括对wi-fi,net等连接的管理）
        ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

        if (connectivityManager == null)
        {
            return false;
        }
        else
        {
            // 获取NetworkInfo对象
            NetworkInfo[] networkInfo = connectivityManager.getAllNetworkInfo();

            if (networkInfo != null && networkInfo.length > 0)
            {
                for (int i = 0; i < networkInfo.length; i++)
                {
                    System.out.println(i + "===状态===" + networkInfo[i].getState());
                    System.out.println(i + "===类型===" + networkInfo[i].getTypeName());
                    // 判断当前网络状态是否为连接状态
                    if (networkInfo[i].getState() == NetworkInfo.State.CONNECTED)
                    {
                        return true;
                    }
                }
            }
        }
        return false;
    }

    @Override
    public void showBigPicture(byte[] bitmap) {


        Bundle bundle = new Bundle();
        bundle.putByteArray("bitmap", bitmap);
        Log.d("showBigPicture","chatActivity");
        overlay(ChatImageShowerActivity.class, bundle);
    }

    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
        byte[] item = (byte[]) adapterView.getItemAtPosition(i);
        if (item!=null){
            //TODO
            Log.d("onItemClick","不为空");
        }
    }
}
